//
//  JXHPhotoBrowserController.swift
//  JXHSinaWeiBo
//
//  Created by juxiaohui on 16/11/14.
//  Copyright © 2016年 juxiaohui. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

let photoBrowserCell = "photoBrowserCell"


class JXHPhotoBrowserController: UIViewController {

    var indexPath : NSIndexPath
    var picURLs : [URL]
    
    lazy var collectionView : UICollectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: JXHPhotoBroweserLayout())
    lazy var closeBtn : UIButton = UIButton()
    lazy var saveBtn : UIButton = UIButton()
    
    init(indexPath : NSIndexPath , picURLs : [URL]) {
        self.indexPath = indexPath
        self.picURLs = picURLs
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 系统回调函数
    override func loadView() {
        super.loadView()
        
        view.frame.size.width += 20
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        // 滚动到对应位置
        collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: false)
    }
}

// MARK: - UI

extension JXHPhotoBrowserController {

    func setupUI() {
        
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        
        collectionView.frame = view.bounds
        
        closeBtn.snp.makeConstraints { (make) in
            make.left.equalTo(20)
            make.bottom.equalTo(-20)
            make.size.equalTo(CGSize.init(width: 90, height: 32))
        }
        
        saveBtn.snp.makeConstraints { (make) in
            make.right.equalTo(-40)
            make.bottom.equalTo(closeBtn.snp.bottom)
            make.size.equalTo(closeBtn.snp.size)
        }
        
        closeBtn.backgroundColor = UIColor.darkGray
        closeBtn.setTitle("关闭", for: .normal)
        closeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)

        saveBtn.backgroundColor = UIColor.darkGray
        saveBtn.setTitle("保存", for: .normal)
        saveBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        
        closeBtn.addTarget(self, action: #selector(JXHPhotoBrowserController.closeBtnClick), for: .touchUpInside)
        saveBtn.addTarget(self, action: #selector(JXHPhotoBrowserController.saveBtnClick), for: .touchUpInside)
        
        collectionView.dataSource = self
//        collectionView.delegate = self
        collectionView.register(JXHPhotoBrowserCell.self, forCellWithReuseIdentifier: photoBrowserCell)
    }
}

// MARK: - 时间监听
extension JXHPhotoBrowserController {
    func closeBtnClick() {
        dismiss(animated: true, completion: nil)
    }
    func saveBtnClick() { //保存图片
       let cell =  collectionView.visibleCells.first as! JXHPhotoBrowserCell
        
        guard let image = cell.imageView.image else {
            return
        }
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(JXHPhotoBrowserController.image(image:didFinishSavingWithError:contextInfo:)), nil)
    }
    
   @objc fileprivate func image(image : UIImage,didFinishSavingWithError : NSError?,contextInfo : Any){
        var showInfo = ""
    
        if didFinishSavingWithError != nil {
            showInfo = "保存失败"
            SVProgressHUD.showError(withStatus: showInfo)
        }else{
            showInfo = "保存成功"
            SVProgressHUD.showSuccess(withStatus: showInfo)
        }
    }
}

// MARK: - collectionView数据源代理

extension JXHPhotoBrowserController : UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picURLs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: photoBrowserCell, for: indexPath) as! JXHPhotoBrowserCell

        cell.picURL = picURLs[indexPath.row]
        cell.delegate = self
        
        return cell
    }
}

// MARK: - JXHPhotoBrowserCellDelegate
extension JXHPhotoBrowserController : JXHPhotoBrowserCellDelegate {
    func imageTapClick() {
        closeBtnClick()
    }
}

extension JXHPhotoBrowserController : JXHPhotoBrowserAnimatorDissmissDelegate {
    

    func indexPathForDissmissView() -> IndexPath? {
        
        let  cell = collectionView.visibleCells.first
        
        return collectionView.indexPath(for: cell!)
        
    }
    
    func imageView() -> UIImageView? {
        
        let  imageView = UIImageView()
        
        let  cell = collectionView.visibleCells.first as! JXHPhotoBrowserCell
 
        imageView.frame = cell.imageView.frame
        imageView.image = cell.imageView.image
        
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        
        return imageView
    }
    
}

// MARK: - 自定义布局
class JXHPhotoBroweserLayout: UICollectionViewFlowLayout {
    
    override func prepare() {
        super.prepare()
        itemSize = collectionView!.frame.size
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal //水平滚动
        //设置collectionView
        collectionView?.isPagingEnabled = true
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
    }
}
